const faker = require("faker");
const dayjs = require("dayjs");

const { Sequelize } = require("sequelize");
const { initModels, User, Todo } = require("../src/models");

// 读取配置文件
const fs = require("fs");
const config = JSON.parse(fs.readFileSync("config.json").toString());
// 初始化 orm
const sequelize = new Sequelize(
  config.database,
  config.username,
  config.password,
  {
    host: "localhost",
    dialect: "mysql",
    port: 3306,
    logging: false,
    define: {
      freezeTableName: true,
      underscored: true,
      timestamps: false,
    },
    dialectOptions: {
      dateStrings: true,
      typeCast: true,
    },
    timezone: "+08:00",
  }
);
// 初始化模型对象
initModels(sequelize);

const { program } = require("commander");
program.version("0.0.1");
program
  .requiredOption("-n, --number <int>", "generate data number")
  .requiredOption(
    "-t, --types [models...]",
    "generate data types: [user | todo]"
  )
  .option("-p, --print", "print json on screen")
  .parse(process.argv);

const options = program.opts();
const range = (n) =>
  Array(parseInt(n))
    .fill()
    .map((_, i) => i);
const rand = (n, start = 0) => Math.floor(Math.random() * n) + start;
const priorities = ["normal", "important", "crucial"];
// main
(async () => {
  let now = dayjs();
  try {
    await sequelize.authenticate();
  } catch (err) {
    console.log(err.message);
  }
  // generate user ...
  if (options.types.includes("user")) {
    for (let _ of range(options.number)) {
      await User.create({
        username: faker.internet.userName(),
        password: "666666",
        nickname: faker.name.findName(),
        createdAt: faker.date.between(
          now.subtract(3, "year"),
          now.subtract(6, "month")
        ),
      });
    }
  }
  // generate todo ...
  if (options.types.includes("todo")) {
    let users = await User.findAll(),
      date = faker.date,
      lorem = faker.lorem;
    for (let user of users) {
      for (let _ of range(options.number)) {
        let createdAt = date.between(user.createdAt, now),
          priority = priorities[rand(3)],
          finished_at = rand(2) == 0 ? date.between(createdAt, now) : null;
        await Todo.create({
          title: lorem.sentence(),
          priority,
          description: lorem.paragraph(),
          finished_at,
          createdAt,
          UserId: user.id,
        });
      }
    }
  }
  // close conn
  await sequelize.close();
})();
